package com.dwd.hrm.exception;

import com.dwd.hrm.util.AjaxResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Description: TODO
 * @Author 汶狄
 * @Date 2021/3/5 11:30
 * @Version 1.0
 */
//可以在controller执行前，后做一些事情@RestControllerAdvice //可以在controller执行前，后做一些事情
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(GlobalException.class)   //处理全局异常异常
    public AjaxResult globalExceptionHandler(GlobalException e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage(e.getMessage()).setStatusCode(SystemError.CODE_400_PARAM_VALID.getCode());
    }

    @ExceptionHandler(Exception.class)   //处理总异常
    public AjaxResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return AjaxResult.me()
                .setSuccess(false)
                .setMessage(SystemError.CODE_500_SYSTEM_ERROR.getMessage())
                .setStatusCode(SystemError.CODE_500_SYSTEM_ERROR.getCode());
    }

    //处理参数校验异常 JSR303
    @ExceptionHandler(MethodArgumentNotValidException.class)//处理GlobalException
    public AjaxResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        e.printStackTrace();
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        fieldErrors.forEach(error -> {
            String field = error.getField();
            String message = error.getDefaultMessage();
            sb.append(field).append(message).append(",");
        });
        return AjaxResult.me()
                .setSuccess(false)
                .setMessage(sb.toString())
                .setStatusCode(SystemError.CODE_400_PARAM_VALID.getCode());

    }

}
